package com.itheima.studentservlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;

@WebServlet("/Student2")
public class Student2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        /*Map<String, String[]> parameterMap = request.getParameterMap();
        //获取学生对象
        Student student = new Student();
        for (String key : parameterMap.keySet()){
            String[] value = parameterMap.get(key);
            //获取属性描述器
            try {
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(key, student.getClass());
                Method writeMethod = propertyDescriptor.getWriteMethod();
                if (value.length>1){
                    writeMethod.invoke(student, (Object) value);
                }else {
                    writeMethod.invoke(student,value);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println(student);*/
        //1.获取所有的数据
        Map<String, String[]> map = request.getParameterMap();

        //2.封装学生对象
        Student stu = new Student();
        //2.1遍历集合
        for(String name : map.keySet()) {
            String[] value = map.get(name);
            try {
                //2.2获取Student对象的属性描述器
                PropertyDescriptor pd = new PropertyDescriptor(name,stu.getClass());
                //2.3获取对应的setXxx方法
                Method writeMethod = pd.getWriteMethod();
                //2.4执行方法
                if(value.length > 1) {
                    writeMethod.invoke(stu,(Object)value);
                }else {
                    writeMethod.invoke(stu,value);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //3.输出对象
        System.out.println(stu);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
